﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Net;

namespace SysSU.Net
{
    class ClientWorker
    {
        private const int END_OF_TRANSMITION = 4;

        private INetworkObserver observer;
        private Socket clientSocket;

        public ClientWorker(INetworkObserver observer, Socket clientSocket)
        {
            this.observer = observer;
            this.clientSocket = clientSocket;
        }

        public void Work()
        {
            try
            {
                var reader = new BinaryReader(new NetworkStream(clientSocket), Encoding.UTF8);
                var writer = new BinaryWriter(new NetworkStream(clientSocket), Encoding.UTF8);

                var message = new StringBuilder();
                int c = -1;
                while ((c = reader.Read()) != END_OF_TRANSMITION)
                {
                    message.Append((char)c);
                }

                var response = observer.Process(
                    new NetworkMessageReceived((IPEndPoint)clientSocket.RemoteEndPoint, message.ToString()));

                if (!String.IsNullOrEmpty(response))
                {
                    writer.Write(response.ToString());
                }

                writer.Write(END_OF_TRANSMITION);
                writer.Flush();
            }
            finally
            {
                clientSocket.Close();
            }
        }
    }
}
